#include "opencv/cv.h"
#include "opencv/highgui.h"

int        g_slider_position = 0;
CvCapture* g_capture         = NULL;

void onTrackbarSlide( int pos ) {
  cvSetCaptureProperty(
      g_capture,
      CV_CAP_PROP_POS_FRAMES,
      pos
  );
}

int main( int argc, char** argv ) {
  cvNamedWindow( "2_PlayAVIVideoControl" );
  g_capture = cvCreateFileCapture( argv[1] );

  int frames = (int) cvGetCaptureProperty(
      g_capture,
      CV_CAP_PROP_FRAME_COUNT
  );

  if ( frames != 0 ) {
      cvCreateTrackbar(
          "Position",
          "2_PlayAVIVideoControl",
          &g_slider_position,
          frames,
          onTrackbarSlide
      );
  }

  IplImage* frame;

  // Once enter into while loop, we are starting read frames
  while(1) {
      // load next frame into memory
      frame = cvQueryFrame( g_capture );
      if ( !frame ) break;

      // Display the frame inside the window
      cvShowImage( "2_PlayAVIVideoControl", frame );

      // Wait for 33ms
      char c = cvWaitKey(33);

      // If user enter Esc key, exit playing the video
      if ( c == 27 ) break;
  }

  cvReleaseCapture( &g_capture );
  cvDestroyWindow( "2_PlayAviVideo" );

  return (0);
}
